<template>
  <div class="homebox">
    <!-- 通用 top head -->
    <img src="@/assets/images/bjd.png" alt="" class="bjd" />
    <Headmain :ymbsid="ymbsid" />
    <div class="tabbox">
      <a-tabs :default-active-key="keyid" @change="changefn">
        <a-tab-pane key="1" title="个人信息">
          <div class="userboxnew">
            <div class="userimgbox"
              ><a-avatar
                :imageUrl="baseurl + userdata.headPortraitUrl.value"
              ></a-avatar
            ></div>
            <div class="userboxtop"></div>
            <div class="userboxtop2"></div>
            <div class="userboxmin">
              <div class="userdes">个人信息</div>
              <div class="userdes2">
                <img src="@/assets/images/Union.png" alt="" />
                <div class="userlabel">姓名：</div>
                <div class="uservalue">{{ userdata.nickname }}</div>
              </div>
              <div class="userdes2">
                <img src="@/assets/images/Union.png" alt="" />
                <div class="userlabel">登录账号：</div>
                <div class="uservalue">{{ userdata.username }}</div>
              </div>
              <div class="userdes2">
                <img src="@/assets/images/layers.png" alt="" />
                <div class="userlabel">所属部门：</div>
                <div class="uservalue"
                  >{{ userdata.groupName }} - {{ userdata.attribute }}</div
                >
              </div>
              <div class="userdes2">
                <img src="@/assets/images/call.png" alt="" />
                <div class="userlabel">联系电话：</div>
                <div class="uservalue">{{ userdata.mobile }}</div>
              </div>
            </div>
            <div class="userbottom" @click="upuserfn"
              >编辑个人信息
              <img src="@/assets/images/rights.png" alt="" class="rights" />
            </div>
          </div>

          <!--  -->
          <!-- 修改头像 和 手机号  -->
          <div class="zlboxmain" v-if="uploadShow">
            <div class="zlboxitem">
              <img
                src="@/assets/images/closefn.png"
                alt=""
                class="closefn"
                @click="uploadCancel"
              />
              <div class="zlboxtitle">修改资料</div>
              <div class="zlboxmainbox">
                <a-form ref="uploadModel" :model="uploadForm">
                  <a-row style="margin-bottom: 16px">
                    <a-form-item field="mobile" label="手机号:">
                      <a-input
                        v-model="uploadForm.mobile"
                        placeholder="请输入手机号"
                        allow-clear
                      />
                    </a-form-item>
                    <a-form-item field="mobile" label="头像:">
                      <a-upload
                        :custom-request="customRequest"
                        :fileList="file ? [file] : []"
                        :show-file-list="false"
                        @change="onChange"
                        @progress="onProgress"
                      >
                        <template #upload-button>
                          <div
                            :class="`arco-upload-list-item${
                              file && file.status === 'error'
                                ? ' arco-upload-list-item-error'
                                : ''
                            }`"
                          >
                            <div
                              class="arco-upload-list-picture custom-upload-avatar"
                              v-if="file && file.url"
                            >
                              <img :src="file.url" />
                              <div class="arco-upload-list-picture-mask">
                                <IconEdit />
                              </div>
                              <a-progress
                                v-if="
                                  file.status === 'uploading' &&
                                  file.percent < 100
                                "
                                :percent="file.percent"
                                type="circle"
                                size="mini"
                                :style="{
                                  position: 'absolute',
                                  left: '50%',
                                  top: '50%',
                                  transform:
                                    'translateX(-50%) translateY(-50%)',
                                }"
                              />
                            </div>
                            <div class="arco-upload-picture-card" v-else>
                              <div class="arco-upload-picture-card-text">
                                <IconPlus />
                                <div style="margin-top: 10px; font-weight: 600"
                                  >上传头像</div
                                >
                              </div>
                            </div>
                          </div>
                        </template>
                      </a-upload>
                    </a-form-item>
                  </a-row>
                </a-form>
              </div>
              <div class="zlboxmainment">
                <div class="zlboxqx" @click="uploadCancel">取消</div>
                <div class="zlboxqd" @click="uploadCheck">确定</div>
              </div>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" title="锁定记录">
          <div class="suodingbox dftable" v-if="renderData">
            <!-- 锁定记录表格 -->

            <a-card class="data-card">
              <a-row>
                <a-col :flex="1">
                  <a-form
                    :model="formModel"
                    :label-col-props="{ span: 6 }"
                    :wrapper-col-props="{ span: 18 }"
                  >
                    <a-row :gutter="20">
                      <!-- <a-col :span="5">
                        <a-form-item field="nicknamee" label="姓名">
                          <a-input
                            v-model="formModel.nickname"
                            placeholder="请输入姓名"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col> -->
                      <a-col :span="5">
                        <a-form-item field="nicknamee" label="日期">
                          <a-range-picker v-model="formModel.datatime" />
                        </a-form-item>
                      </a-col>
                      <!-- <a-col :span="5">
                        <a-form-item field="groupNamezh" label="组织">
                          <a-cascader
                            v-model="formModel.deptId"
                            check-strictly
                            :options="organizations"
                            placeholder="请选择所在组织"
                            :field-names="organizationsFields"
                            :show-all-levels="false"
                            @change="changsd"
                            allow-clear
                          ></a-cascader>
                        </a-form-item>
                      </a-col> -->
                      <a-col :span="5">
                        <a-space :size="18">
                          <a-button type="primary" @click="onPageChange(1)">
                            <template #icon>
                              <icon-search />
                            </template>
                            搜索
                          </a-button>
                          <a-button @click="reset">
                            <template #icon>
                              <icon-refresh />
                            </template>
                            重置
                          </a-button>
                        </a-space>
                      </a-col>
                    </a-row>
                  </a-form>
                </a-col>
              </a-row>
              <a-table
                ref="userList"
                row-key="userId"
                :loading="loading"
                page-position="bottom"
                :pagination="pagination"
                v-model:selectedKeys="userIds"
                :columns="columns"
                :data="renderData"
                :bordered="false"
                @page-change="onPageChange"
                @page-size-change="onPageSizeChange"
              >
                <template #startTime="{ record }">
                  {{ record.startTime }}~{{ record.endTime }}
                </template>
              </a-table>
            </a-card>
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" title="通知消息">
          <div class="suodingbox dftables" v-if="renderDatas">
            <!-- 锁定记录表格 -->
            <a-card class="data-card">
              <a-table
                ref="userList"
                row-key="userId"
                :loading="loading"
                page-position="bottom"
                :pagination="paginations"
                v-model:selectedKeys="userIds"
                :columns="columnss"
                :show-header="false"
                :data="renderDatas"
                :bordered="false"
                @page-change="onPageChange"
                @page-size-change="onPageSizeChange"
              >
                <template #notifyId="{ record }">
                  <div class="notibox" @click="gotipxq(record)">
                    <div
                      :class="record.readStatus == 9 ? 'tipbs' : 'tipbss'"
                    ></div>
                    <div class="titlebox">{{ record.title }}</div>
                    <div class="titletimer">{{ record.createTime }}</div>
                  </div>
                </template>
              </a-table>
            </a-card>
          </div>
          <!-- 患者信息表格 -->
          <div class="hzdesmainbox" v-if="addFormshow">
            <div class="hzdesmain">
              <img
                src="@/assets/images/closefn.png"
                alt=""
                class="closefn"
                @click="addFormshow = false"
              />
              <div class="hzdesmainitem">
                <div class="dayhzmain">
                  <div class="dayhzimg">
                    <img src="@/assets/images/hztx.png" alt="" />
                  </div>
                  <div class="dayhzdesbox">
                    <div class="dayhznamebox dayhznameboxs">
                      <div class="dayhznamelabel">姓名</div>
                      <div class="dayhzname">{{ addForm.patientName }}</div>
                    </div>
                    <div class="dayhznamebox">
                      <div class="dayhznamelabel">性别</div>
                      <div class="dayhzname">
                        {{ addForm.patientSex == 'F' ? '男' : '女' }}</div
                      >
                    </div>
                    <div class="dayhznamebox">
                      <div class="dayhznamelabel">身份证号</div>
                      <div class="dayhzname">{{ addForm.idCard }}</div>
                    </div>
                    <div class="dayhznamebox">
                      <div class="dayhznamelabel">联系方式</div>
                      <div class="dayhzname"> {{ addForm.mobile }}</div>
                    </div>
                    <div class="dayhznamebox">
                      <div class="dayhznamelabel">患者年龄</div>
                      <div class="dayhzname"> {{ addForm.patientAge }}</div>
                    </div>
                    <div class="dayhznamebox">
                      <div class="dayhznamelabel">床位号</div>
                      <div class="dayhzname">{{ addForm.bedNumber }}</div>
                    </div>
                    <div class="dayhznamebox">
                      <div class="dayhznamelabel">分配人</div>
                      <div class="dayhzname">{{ addForm.assignUser }}</div>
                    </div>
                    <div class="dayhznamebox">
                      <div class="dayhznamelabel">分配时间</div>
                      <div class="dayhzname">{{ addForm.createTime }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="closefnbox" @click="addFormshow = false"
                >关闭窗口</div
              >
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import Headmain from '../headmain/headmain.vue';
  import { storeToRefs } from 'pinia';
  import { Message, Modal } from '@arco-design/web-vue';
  import { useSelectionStore, useUserStore } from '@/store';
  import {
    uploadFile,
    updateInfo,
    patientInfo,
    restList,
    notifyList,
    notifyRead,
  } from '@/api/user';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import useUser from '@/hooks/user';
  import useLoading from '@/hooks/loading';
  import { organizationTree } from '@/api/organization.ts';
  import { useRoute } from 'vue-router';

  const { loading, setLoading } = useLoading(true);
  const { logout } = useUser();
  const userStore = useUserStore();
  const userdata = storeToRefs(userStore);
  console.log('获取当前用户信息', userdata.mobile);
  const keyid = ref('1');
  // 定义当页面标识
  const ymbsid = ref('4');

  const uploadShow = ref(false);
  const uploadCancel = () => {
    uploadShow.value = false;
    keyid.value = '1';
  };
  const uploadModel = ref();
  const uploadForm = ref([]);
  const uploadCheck = (done) => {
    // if (loading.value) {
    //   done(false);
    //   return;
    // }

    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);

    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          updateInfo({ ...uploadForm.value }).then(async (res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '修改成功!',
              });
              uploadForm.value = [];

              uploadShow.value = false;
              await userStore.info(); // 调用 info() 获取用户信息
              done(true);
            } else {
              Message.success({
                //   content: res.message,
                content: res.message,
              });
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const file = ref();

  const onChange = (_, currentFile) => {
    file.value = {
      ...currentFile,
      // url: URL.createObjectURL(currentFile.file),
    };
  };
  const onProgress = (currentFile) => {
    file.value = currentFile;
    // console.log('currentFile', file.value);
  };
  const customRequest = (currentFile) => {
    file.value = currentFile;
    // console.log('currentFile', file.value.fileItem);
    let formData = new FormData();
    formData.append('file', file.value.fileItem.file);
    uploadFile(formData).then((res) => {
      if (res.code == 200) {
        uploadForm.value.headPortraitUrl = res.data;
      }
    });
  };
  const upuserfn = () => {
    uploadShow.value = true;
    uploadForm.value.mobile = userdata.mobile.value;
    uploadForm.value.headPortraitUrl = userdata.headPortraitUrl.value;
  };
  const baseurl = ref();
  baseurl.value = window.config.VUE_APP_BASE_IMG;
  // console.log('当前及地址', baseurl.value);

  const userimg = ref();
  userimg.value = baseurl.value + userdata.headPortraitUrl.value;

  // 监听keyid
  // watch(keyid, (i) => {
  //   console.log('我触发啦！', i);
  // });
  const changefn = (id) => {
    console.log('执行了', id);
    keyid.value = id;
    if (id == 2) {
      fetchData();
    }
    if (id == 3) {
      fetchDatas();
    }
  };

  const generateFormModel = () => {
    return {
      nickname: '',
      datatime: '',
      groupName: '',
      attribute: '',
      deptId: '',
    };
  };

  const organizations = ref([]);

  const getOrganizations = () => {
    organizationTree().then((res) => {
      organizations.value = res.data || [];
    });
  };
  getOrganizations();
  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const renderDatas = ref([]);
  const userList = ref();
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });

  const basePaginations: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const paginations = reactive({
    ...basePaginations,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        nickname: formModel.value.nickname,
        groupName: formModel.value.groupName,
        attribute: formModel.value.attribute,
        startDate: formModel.value.datatime[0],
        endDate: formModel.value.datatime[1],
      };
      restList(data).then((res) => {
        renderData.value = res.data.list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  const onPageChanges = (current: number) => {
    paginations.current = current;
    fetchDatas();
  };
  const onPageSizeChanges = (pageSize: number) => {
    paginations.pageSize = pageSize;
    fetchDatas();
  };

  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const rowSelections = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '序号',
      dataIndex: 'restId',
    },
    {
      title: '锁定时间',
      dataIndex: 'startTime',
      slotName: 'startTime',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '时长',
      dataIndex: 'duration',
      // slotName: 'sex',
      // align: 'center',
    },
  ]);

  const columnss = computed<TableColumnData[]>(() => [
    {
      title: '插槽',
      dataIndex: 'notifyId',
      slotName: 'notifyId',
    },
  ]);
  const userIds = ref();
  const organizationsFields = {
    value: 'id',
    label: 'name',
  };
  const changsd = (value) => {
    formModel.value.groupName = '';
    formModel.value.attribute = '';
    function findParentIdById(idToFind) {
      for (let i = 0; i < organizations.value.length; i++) {
        const item = organizations.value[i];
        if (item.id === idToFind) {
          return item.parentId;
        }
        if (item.children) {
          for (let j = 0; j < item.children.length; j++) {
            const childItem = item.children[j];
            if (childItem.id === idToFind) {
              return item.id;
            }
            if (childItem.children) {
              for (let k = 0; k < childItem.children.length; k++) {
                const grandChildItem = childItem.children[k];
                if (grandChildItem.id === idToFind) {
                  return childItem.id;
                }
              }
            }
          }
        }
      }
      return null;
    }
    const parentId = findParentIdById(value);

    formModel.value.attribute = value;
    formModel.value.groupName = parentId;
    if (parentId == 0) {
      formModel.value.attribute = '';
      formModel.value.groupName = value;
    }
  };

  const fetchDatas = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: paginations.current,
        ...paginations,
      };
      notifyList(data).then((res) => {
        renderDatas.value = res.data.list;
        paginations.total = res.data.total;
        paginations.current = res.data.pageNum;
        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  const addFormshow = ref(false);
  const addForm = ref({
    assignUser: '',
  });
  const gotipxq = (item) => {
    // 查询患者信息
    patientInfo({ patientId: item.patientId }).then((res) => {
      if (res.code == 200) {
        console.log('查询患者信息', res.data);
        addForm.value = res.data;
        addForm.value.assignUser = item.assignUser;
      }
    });
    notifyRead({
      notifyId: item.notifyId,
    }).then((res) => {
      if (res.code == 200) {
        fetchDatas();
        addFormshow.value = true;
      }
    });
  };
  const route = useRoute();

  changefn(route.query.id);
</script>

<style scoped>
  .dftable .data-card {
    width: 1630px;
    height: 794px;
    background: rgba(255, 255, 255, 0.5);
    border-radius: 20px 20px 20px 20px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    margin: 0 auto;
    overflow: hidden;
    overflow-y: auto;
  }
  .dftables .data-card {
    width: 1630px;
    height: 794px;
    background: rgba(255, 255, 255, 0.5);
    border-radius: 20px 20px 20px 20px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    margin: 0 auto;
    overflow: hidden;
    overflow-y: auto;
  }
  .closefnbox {
    width: 134px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #1e657b;
    position: absolute;
    left: 50%;
    bottom: 30px;
    transform: translate(-50%, 0);
    font-size: 20px;
    color: #1e657b;
    cursor: pointer;
  }
</style>
